let colorMath = ['#f47a55', '#53261f', '#121a2a', '#694d9f', '#411445', '#2f271d', '#009ad6', '#1b315e', '#6a3427']
// 常用工具函数
/**
 * 休眠xxxms
 * @param {Number} milliseconds
 */
export function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}
//使用方式
// const fetchData=async()=>{
// 	await sleep(1000)
// }


/**
 * 生成随机id
 * @param {*} length
 * @param {*} chars
 */
export function createUUid(length, chars) {
    chars =
        chars ||
        '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    length = length || 8
    var result = ''
    for (var i = length; i > 0; --i)
        result += chars[Math.floor(Math.random() * chars.length)]
    return result
}
/**
 * 为数组生成id
 * @param {*} data
 * @param {*} idFiled
 * @param {*} childFiled
 */
export function arrByCreateUUid(data, idFiled = "id", childFiled = "children", ) {
    data.forEach(item => {
        item[idFiled] = createUUid()
        if (item[childFiled] && item[childFiled].length > 0)
            item[childFiled].forEach($item => {
                $item[idFiled] = createUUid()
                if ($item[childFiled] && $item[childFiled].length > 0) {
                    arrByCreateUUid($item[childFiled], childFiled)
                }
            })
    })
    return data
}

/**
 * 数组去重
 * @param {*} arr
 */
export function uniqueArray(arr) {
    if (!Array.isArray(arr)) {
        throw new Error('The first parameter must be an array')
    }
    if (arr.length == 1) {
        return arr
    }
    return [...new Set(arr)]
}

/**
 * 对象转化为formdata
 * @param {Object} object
 */

export function getFormData(object) {
    const formData = new FormData()
    Object.keys(object).forEach(key => {
        const value = object[key]
        if (Array.isArray(value)) {
            value.forEach((subValue, i) =>
                formData.append(key + `[${i}]`, subValue)
            )
        } else {
            formData.append(key, object[key])
        }
    })
    return formData
}
/**
 * 获取文件后缀名
 * @param {String} filename
 */
export function getExt(filename) {
    if (typeof filename == 'string') {
        return filename
            .split('.')
            .pop()
            .toLowerCase()
    } else {
        throw new Error('filename must be a string type')
    }
}

/**
 * 复制内容到剪贴板
 * @param {String} value
 */
export function copyToBoard(value) {
    const element = document.createElement('textarea')
    document.body.appendChild(element)
    element.value = value
    element.select()
    if (document.execCommand('copy')) {
        document.execCommand('copy')
        document.body.removeChild(element)
        return true
    }
    document.body.removeChild(element)
    return false
}

/**
 * 下载自己创建的的文件
 * @param {String} name 文件名
 * @param {String} content 文件内容
 */
export function downloadFile(name, content) {
    if (typeof name == 'undefined') {
        throw new Error('The first parameter name is a must')
    }
    if (typeof content == 'undefined') {
        throw new Error('The second parameter content is a must')
    }
    if (!(content instanceof Blob)) {
        content = new Blob([content])
    }
    const link = URL.createObjectURL(content)
    download(link, name)
}
/**
 * 浏览器下载静态文件
 * @param {String} link 文件地址
 * @param {String} name 文件名
 */
function download(link, name) {
    if (!name) { //如果没有提供名字，从给的Link中截取最后一坨
        name = link.slice(link.lastIndexOf('/') + 1)
    }
    let eleLink = document.createElement('a')
    eleLink.download = name
    eleLink.style.display = 'none'
    eleLink.href = link
    document.body.appendChild(eleLink)
    eleLink.click()
    document.body.removeChild(eleLink)
}

/**
 * 防抖
 * @param {*} func 要进行防抖的函数
 * @param {*} wait 等待时间,默认500ms
 * @param {*} immediate 是否立即执行
 */
export function debounce(func, wait = 500, immediate = false) {
    var timeout
    return function () {
        var context = this
        var args = arguments

        if (timeout) clearTimeout(timeout)
        if (immediate) {
            // 如果已经执行过，不再执行
            var callNow = !timeout
            timeout = setTimeout(function () {
                timeout = null
            }, wait)
            if (callNow) func.apply(context, args)
        } else {
            timeout = setTimeout(function () {
                func.apply(context, args)
            }, wait)
        }
    }
}

/**
 * 节流，多次触发，间隔时间段执行
 * @param {Function} func
 * @param {Int} wait
 * @param {Object} options
 */
export function throttle(func, wait = 500, options) {
    //container.onmousemove = throttle(getUserAction, 1000);
    var timeout, context, args
    var previous = 0
    if (!options) options = {
        leading: false,
        trailing: true
    }

    var later = function () {
        previous = options.leading === false ? 0 : new Date().getTime()
        timeout = null
        func.apply(context, args)
        if (!timeout) context = args = null
    }

    var throttled = function () {
        var now = new Date().getTime()
        if (!previous && options.leading === false) previous = now
        var remaining = wait - (now - previous)
        context = this
        args = arguments
        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout)
                timeout = null
            }
            previous = now
            func.apply(context, args)
            if (!timeout) context = args = null
        } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(later, remaining)
        }
    }
    return throttled
}


/**
 * 移除数组中的空值
 * @param  {} array 必填：要移除的数组
 */
export const arrTrim = (array) => {
    if (!Array.isArray(array)) {
        return console.log(`您输入的数据类型不正确`)
    }
    for (let i = 0; i < array.length; i++) {
        if (array[i] == "" || typeof array[i] == "undefined") {
            array.splice(i, 1);
            i = i - 1;
        }
    }
    return array;
}

/**
 * 数组根据下面对象的某一个字段进行排序 this.tableData.sort(arrSort(sort.prop,bol))
 * @param  {} field 必填：对象的字段
 * @param  {} bol 可选：true是降序，false为升序 默认为降序
 */
export const arrSort = (field, bol = true) => {
    return function (a, b) {
        let i = a[field];
        let j = b[field];
        if (bol) return i - j;
        if (!bol) return j - i;
    };
}


/**
 * 数组 或者 字符串去重
 * @param  {} data 必填, 数组的字段
 * @param  {} sym  可选，如果是字符串的话，字符串用什么符号来分割,默认是逗号
 */
export const removeRepeat = (data, sym = ',') => {
    if (typeof data == 'string') {
        let arr = data.split(sym)
        return [...new Set(arr)].join(sym);
    }
    if (Array.isArray(data)) {
        return [...new Set(data)];
    }
    return console.log(`您输入的数据类型不正确`)
}

/**
 * 数组里面是否有重复，有重复把重复的字提取出来
 * @param  {} data  
 * @param  {} sym  可选，字符串用什么符号来分割,默认是逗号
 */

export function getRepeat(data, sym = '，') {
    if (typeof data == 'string') {
        let arr = data.split(sym)
        let isRepate = arr.length == removeRepeat(arr).length ? false : true
        //没有重复的，直接返回false
        if (!isRepate) return {
            isRepate: false,
            len: arr.length
        }
        //发现重复的
        return _getRepeatFun(arr)
    }
    if (Array.isArray(data)) {
        let isRepate = data.length == removeRepeat(data).length ? false : true
        //没有重复的，直接返回false
        if (!isRepate) return {
            isRepate: false,
            len: arr.length
        }
        //发现重复的
        return _getRepeatFun(data)
    }
}
// 获取重复的 数据统计
export function _getRepeatFun(arr) {
    // index 重复的位置 
    // num   重复的数量
    // content 重复的内容
    // color 重复的颜色
    let repeatData = []
    let newArr = []
    arr.forEach((content, index) => {
        let newItem = newArr.find(item => {
            return item.content == content
        })
        if (newItem) {
            let idx = repeatData.findIndex(item => {
                return item.content == newItem.content
            })
            if (idx > -1) {
                repeatData[idx].index = repeatData[idx].index + ',' + (index + 1)
                repeatData[idx].num = repeatData[idx].num + 1

            } else {
                let len = repeatData.length
                let repeatObj = {
                    index: newItem.index + "," + (index + 1),
                    content: newItem.content,
                    num: 2,
                    color: colorMath[len]
                }
                repeatData.push(repeatObj)
            }

        } else {
            newArr.push({
                content,
                index: index + 1
            })
        }

    })
    let handleData = []
    arr.forEach((name) => {
        let $item = {
            name,
            color: ''
        }
        let item = repeatData.find(item => {
            return item.content == name
        })
        if (item) $item.color = item.color
        handleData.push($item)
    })

    let res = {}
    res.repeat = repeatData
    res.data = handleData
    res.len = arr.length
    res.repeatLen = [...new Set(arr)].length
    res.isRepate = true
    return res;

}

// 分页构造函数
export class PagingFun {
    constructor(data) {
        this.pagingData = [];
        this.data = []
        this.tatal = 0
        this.paging(data)
    }
    // 初始化分页数据
    paging(data) {
        this.pagingData = this.gruopData(data);
        this.data = this.pagingData[0];
        this.tatal = this.pagingData.length;
        return {
            data: this.data, // 第一页的数据,
            tatal: this.tatal //总页数
        }
    }
    // 对获取的数据进行分页
    gruopData(data) {
        let arr = [];
        let items = null;
        data.forEach((item, index) => {
            if (index % 100 == 0) {
                items != null && arr.push(items);
                items = [];
            }
            items.push(item);
        });
        arr.push(items);
        return arr;
    }
    // 分两种 
    // 1 点击加载第二页
    // 2 滚动加载，滚动加载
    //分页加载数据
    loadData(page = 1) {
        if (page >= this.tatal) return false;
        let data = this.data;
        this.data = data.concat(this.pagingData[page]);
        this.page = this.page + 1;
    }
    //绑定滚动加载
    bindScroll($dom) {
        let dom = $dom.bodyWrapper;
        dom.addEventListener("scroll", () => {
            let scrollTop = dom.scrollTop; //滚动的距离
            let tableHeight = dom.clientHeight; //table的高度
            let scrollHieght = dom.scrollHeight; // 滚动条高度
            if (scrollTop + tableHeight == scrollHieght) {
                this.loadData(this.page);
            }
        });
    }
    scrollLoadData(page = 1) {
        if (page >= this.tatal) return false;
        Array.prototype.push.apply(this.data, this.pagingData[page]);
        this.page = this.page + 1;
    }
}